<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link href="../../component/layui/css/layui.css" rel="stylesheet" />
    <link href="../../admin/css/pearCommon.css" rel="stylesheet" />
</head>

<body>

    <body class="pear-container">
        <div class="layui-card">
            <div class="layui-card-body">
                <form action="" class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">专题名称</label>
                        <div class="layui-input-inline">
                            <input class="layui-input" id="demoReload" name="specName" placeholder="" type="text">
                        </div>
                        <a class="pear-btn pear-btn-md pear-btn-primary" data-type="reload" id="featureSearch" lay-filter="user-query" lay-submit>
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </a>
                        <button class="pear-btn pear-btn-md" id="featureReset" type="reset">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-body">
                <table id="user-table" lay-filter="user-table"></table>
            </div>
        </div>
    </body>
    <!--		新增开始 -->
    <div class="site-text" id="spec-window" style="margin: 5%; display: none" target="test123">
        <form class="layui-form" id="scene-add">
            <div class="layui-form-item">
                <label class="layui-form-label">专题图名称</label>
                <div class="layui-input-block">
                    <input autocomplete="off" class="layui-input" id="realName" lay-verify="required" maxlength="50" name="title" placeholder="请输入" required type="text">
                    <input id="status" name="status" type="hidden" value="1">
                    <div class="layui-form-mid layui-word-aux" id="inputRealName">必填项</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">专题图描述</label>
                <div class="layui-input-block">
                    <textarea class="layui-textarea" id="specDesc" maxlength="200" name="desc" placeholder="请输入"></textarea>
                </div>
            </div>
        </form>
    </div>
    <!--        新增结束-->
    <!--<script id="user-toolbar" type="text/html">-->
    <!--    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">-->
    <!--        <i class="layui-icon layui-icon-add-1"></i>-->
    <!--        创建专题地图-->
    <!--    </button>-->
    <!--</script>-->

    <script id="user-bar" type="text/html">
        <input type="checkbox" name="enable" valueId="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="user-enable" {{d.status=="1" ? "checked" : "" }}>
        <!--    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>-->
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script id="user-edit" type="text/html">

    </script>
    <script id="user-enable" type="text/html">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="start">启用</a>
    </script>

    <script id="icon" type="text/html">
        <i class="layui-icon {{d.icon}}"></i>
    </script>

    <script id="service-status" type="text/html">
        {{#if (d.status == 1) { }}
        <span style="color: #338528;">启用</span> {{# }else if(d.status == 0){ }}
        <span>停用</span> {{# } }}
    </script>
    <script id="user-createTime" type="text/html">
        {{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}
    </script>

    <script src="../../component/layui/layui.js"></script>

    <script>
        var projectManageObj = {};
        layui.use(['table', 'form', 'jquery'], function() {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.jquery;

            let MODULE_PATH = "/system/user/";

            let cols = [
                    [
                        // {type:'checkbox'},
                        // {title: '缩略图', field: 'icon', templet: '#icon', align: 'center', width: 80},
                        {
                            title: '专题模块',
                            field: 'specModule',
                            sort: true,
                            align: 'center'
                        }, {
                            title: '专题名称',
                            field: 'specName',
                            sort: true,
                            align: 'center'
                        }, {
                            title: '专题描述',
                            field: 'specDesc',
                            align: 'center'
                        }, {
                            title: '专题状态',
                            field: 'status',
                            sort: true,
                            align: 'center',
                            templet: '#service-status'
                        },
                        // {title: '场景状态', field: 'enable', align:'center', templet:'#user-enable'},
                        {
                            title: '创建时间',
                            field: 'createTime',
                            sort: true,
                            align: 'center',
                            templet: '#user-createTime'
                        }, {
                            title: '更新时间',
                            field: 'updateTime',
                            sort: true,
                            align: 'center',
                            templet: '#user-createTime'
                        }, {
                            title: '操作',
                            toolbar: '#user-bar',
                            fixed: 'right',
                            align: 'center',
                            width: 300
                        }
                    ]
                ]
                /*
                 *   图层编辑
                 *   表单数据
                 */
            table.render({
                elem: '#demo',
                height: 420,
                url: '/element/viewBusinessProperty', //数据接口
                title: '用户表',
                page: true, //开启分页
                toolbar: 'default', //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                totalRow: true, //开启合计行
                cols: [
                    [ //表头
                        {
                            field: 'id',
                            title: 'ID',
                            width: 80,
                            sort: true,
                            fixed: 'left',
                            totalRowText: '合计：'
                        }, {
                            field: 'username',
                            title: '名称',
                            width: 80
                        }, {
                            field: 'experience',
                            title: '类型',
                            width: 90,
                            sort: true,
                            totalRow: true
                        }, {
                            field: 'address',
                            title: '地址/所在社区',
                            width: 80,
                            sort: true
                        }
                    ]
                ]
            });
            table.render({
                elem: '#user-table',
                url: '/one/specSubManager/list',
                method: 'post',
                contentType: 'application/json',
                where: {
                    order: 3,
                    orderDesc: 0        
                },
                request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                        ,
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                parseData: function(res) { //res 即为原始返回的数据
                    return {
                        "createTime": null,
                        "createBy": null,
                        "updateTime": null,
                        "updateBy": null,
                        "remark": null,
                        "code": 200,
                        "msg": "...",
                        "count": res.data.total,
                        "data": res.data.list
                    }
                },
                id: 'user-table',
                page: true,
                cols: cols,
                skin: 'line',
                toolbar: '#user-toolbar',
                response: {
                    statusCode: 200 //成功的状态码，默认：0
                },
                initSort: {
                    field: 'createTime',
                    type: 'desc',
			    },
                defaultToolbar: [{
                        layEvent: 'refresh',
                        icon: 'layui-icon-refresh',
                        title:'刷新'
                    }, 'filter'] //, 'print', 'exports'
            });

            table.on('sort(user-table)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                // console.log(obj.field); //当前排序的字段名
                // console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

                var field = obj.field;
                var type = obj.type;
                var order = 1;
                var orderDesc = 0;
                if (field === 'createTime') {
                    order = 3;
                } else if (field === 'updateTime') {
                    order = 2;
                }

                if (type === "asc") {
                    orderDesc = 1
                } else if (type == "desc") {
                    orderDesc = 0;
                } else {
                    orderDesc = 0;
                    order = 2;
                }

                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                table.reload('user-table', {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                        ,
                    where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        order: order //排序字段   在接口作为参数字段  field order
                            ,
                        orderDesc: orderDesc //排序方式   在接口作为参数字段  field order
                    }
                });
            });

            table.on('tool(user-table)', function(obj) {
                // if (obj.event === 'remove') {
                //     window.remove(obj);
                // } else
                if (obj.event === 'edit') {
                    window.edit(obj);
                }else if(obj.event === 'del'){
                    projectManageObj.del(obj);
                }
            });

            table.on('toolbar(user-table)', function(obj) {
                // if (obj.event === 'add') {
                //     window.add();
                // } else
                if (obj.event === 'refresh') {
                    window.refresh();
                } else if (obj.event === 'batchRemove') {
                    window.batchRemove(obj);
                }
            });
            form.on('submit(user-query)', function(data) {
                // table.reload('user-table', {where: data.field})
                // return false;
            });

            form.on('switch(user-enable)', function(obj) {
                var switch_id = obj.elem.attributes['valueId'].nodeValue;
                // var switch_id = table.checkStatus('user-table');//表格id，获取选中行
                var validFlag = Number(obj.elem.checked); //转为 0、1
                console.log(validFlag);
                $.ajax({
                    url: "/one/specSubManager/enableOrDisabled",
                    type: "POST",
                    data: JSON.stringify({
                        id: switch_id,
                        status: validFlag
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    success: function(data) {
                        if (data.errorCode === '401') {
                            loginStatusIntercept(data.msg)
                            return
                        }
                        if (data.success) {
                            table.reload('user-table');
                            console.log(obj.elem.checked);
                            // obj.elem.checked = !obj.elem.checked;
                            layer.msg('专题图状态：' + (obj.elem.checked ? '启用' : '禁用'), {
                                icon: 1
                            });
                        } else {
                            layer.msg("失败,失败原因:" + data.msg, {
                                icon: 2
                            });
                            table.reload('user-table');
                        }
                    }
                });
                //  form.render('checkbox');
            });

            // window.add = function () {
            //     layer.open({
            //         type: 1,
            //         title: '添加专题地图',
            //         shade: 0.1,
            //         area: ['60%', '480px'],
            //         content: $('#real-window'),
            // 		resize: true,
            // 		btn: ['保存', '取消'],
            //         success:function(layero,index){
            //             // $('#realName').show();
            //             // $('#phone').show();
            //
            //         },
            //         yes:function(index,layero){
            //
            //         }
            //     });
            // }

            // window.edit = function (obj) {
            //     layer.open({
            //         type: 1,
            //         title: '修改',
            //         shade: 0.1,
            //         area: ['600px', '400px'],
            //         content: MODULE_PATH + 'edit?userId=' + obj.data['userId'],
            //         content: $('#spec-window'),
            //         resize: true,
            //         btn:['确定','取消'],
            //         success:function(layero,index){
            //             $('#realName').val(data.realName);
            //             $('#phone').val(data.phone);
            //         },
            //         yes:function(index,layero){
            //
            //         }
            //     });
            // }
            projectManageObj.del = function(obj){
                var data = obj.data;//获得当前行数据
                layer.confirm('确认删除该专题吗？', {icon: 3, title:'提示'}, function(index){
                    let ids = data.id;
                    $.ajax({
                        url: "/one/specSubManager"+"?ids="+ids,
                        type: "DELETE",
                        // data:{ids:ids},
                        dataType: "json",
                        success: function(data){
                            if (data.errorCode === '401') {
                                loginStatusIntercept(data.msg)
                                return
                            }
                            if(data.errorCode==0){
                                //删除这一行
                                obj.del();
                                //关闭弹框
                                layer.close(index);
                                layer.msg("删除成功", {icon: 6});
                                table.reload('user-table');
                            }else{
                                layer.msg("删除失败", {icon: 5});
                            }
                        }
                    });
                });
		    };
            window.edit = function(obj) {
                var data = obj.data;
                console.log(data);
                layer.open({
                    type: 1,
                    title: '修改自定义要素',
                    shade: 0.1, //遮罩透明度
                    area: ['60%', '60%'],
                    content: $('#spec-window'),
                    resize: true,
                    btn: ['确定', '取消'],
                    success: function(layero, index) {
                        $('#realName').val(data.specName);
                        $('#specDesc').val(data.specDesc);
                    },
                    yes: function(index, layero) {
                        var realName = $("#realName").val();
                        if (realName == '') {
                            layer.msg('要素名称不能为空', {
                                icon: 2,
                                time: 1000
                            });
                            return;
                        }
                        $.ajax({
                            url: "/one/specSubManager/update",
                            type: "POST",
                            data: JSON.stringify({
                                specName: $('#realName').val(),
                                specDesc: $('#specDesc').val(),
                                id: data.id,
                            }),
                            dataType: "json",
                            contentType: "application/json; charset=UTF-8",
                            success: function(data) {
                                if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                                if (data.success) {
                                    layer.alert('修改成功', {
                                        icon: 1,
                                        title: '提示'
                                    }, function(i) {
                                        layer.close(i);
                                        layer.close(index); //关闭弹出层
                                        $("#fm")[0].reset() //重置form
                                    });
                                    table.reload('user-table', { //重载表格
                                        page: {
                                            curr: obj.curr
                                        }
                                    })
                                } else {
                                    layer.msg("修改失败,失败原因:" + data.msg, {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    }
                });
            }
            $("#demoReload").unbind("keydown").keydown(function (e) {//当按下按键时
                e.stopPropagation()
                var key = e.keyCode || e.charCode || e.which;
                if (key == 13) {
                    e.preventDefault()
                    $("#featureSearch").trigger('click');
                }
            })
            $('#featureSearch').on('click', function() {
                var active = {
                    reload: function() {
                        var demoReload = $('#demoReload');
                        //执行重载
                        table.reload('user-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                specName: demoReload.val()
                            }
                        }, 'data');
                    }
                };
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });


            $('#featureReset').on('click', function() {

                var demoReload = $('#demoReload');
                demoReload.val("")
                    //执行重载
                table.reload('user-table', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        specName: demoReload.val()
                    }
                }, 'data');


            });

            // window.batchRemove = function (obj) {
            //     let data = table.checkStatus(obj.config.id).data;
            //     if (data.length === 0) {
            //         layer.msg("未选中数据", {icon: 3, time: 1000});
            //         return false;
            //     }
            //     let ids = "";
            //     for (let i = 0; i < data.length; i++) {
            //         ids += data[i].userId + ",";
            //     }
            //     ids = ids.substr(0, ids.length - 1);
            //     layer.confirm('确定要删除这些用户', {icon: 3, title: '提示'}, function (index) {
            //         layer.close(index);
            //         let loading = layer.load();
            //         $.ajax({
            //             url: MODULE_PATH + "batchRemove/" + ids,
            //             dataType: 'json',
            //             type: 'delete',
            //             success: function (result) {
            //                 layer.close(loading);
            //                 if (result.success) {
            //                     layer.msg(result.msg, {icon: 1, time: 1000}, function () {
            //                         table.reload('user-table');
            //                     });
            //                 } else {
            //                     layer.msg(result.msg, {icon: 2, time: 1000});
            //                 }
            //             }
            //         })
            //     });
            // }

            window.refresh = function(param) {
                table.reload('user-table');
            }
        })
    </script>
</body>

</html>
